package com.lmscn.lms.api.controller;

import com.jfinal.aop.Before;
import com.jfinal.core.Controller;
import com.jfinal.plugin.activerecord.Page;
import com.lmscn.lms.api.interceptor.Condition;
import com.lmscn.lms.api.interceptor.KeyCondition;
import com.lmscn.lms.api.model.*;
import com.lmscn.lms.api.util.CommonUtil;
import com.lmscn.lms.api.util.DateUtil;
import com.lmscn.lms.api.util.JsonKit;
import com.lmscn.lms.api.util.NumberUtil;
import com.lmscn.lms.commons.GlobalConst;

import java.util.*;

import org.apache.log4j.Logger;


/**
 * Created by Czl on 2015/7/24.
 */
public class CourseBaseController extends Controller {

    public Condition cond;
    public KeyCondition kcd;

    Logger log = Logger.getLogger(CourseBaseController.class);

    /**
     * APP头部banner
     * http://localhost:8080/api/course/getBanners?type=1
     * @date 2016年11月10日11:14:52
     */
    public void getBanners() {
        Map<String, Object> dataMap = new HashMap<String, Object>();

        // banner的类型，首页banner为0，二级页面为2；
        // 待定 2016年11月13日16:59:52
        // 修改：2016年12月2日13:24:57 类型：0：首页；1：微课页；
        int type = getParaToInt("type");

        // 设置显示多少张
        int nums = Integer.parseInt(SysDictData.dao.findByItem("banner_nums").getStr("dd_value"));

        int i=0;
        List<BannerImages> bannerImagesList = BannerImages.dao.findBanners(nums, type, "course");
        if (bannerImagesList != null) {
            for (BannerImages bannerImages : bannerImagesList) {
//				bannerImages.set("img_url", CommonUtil.getBannerUrl(bannerImages));
//                bannerImages.set("img_url",
//                        i==0 ? "https://t7.baidu.com/it/u=1956604245,3662848045&fm=193&f=GIF"
//                                : i==1 ? "https://t7.baidu.com/it/u=3779234486,1094031034&fm=193&f=GIF"
//                                : i==2 ? "https://t7.baidu.com/it/u=3435942975,1552946865&fm=193&f=GIF"
//                                : i==3 ? "https://t7.baidu.com/it/u=3569419905,626536365&fm=193&f=GIF"
//                                : "https://t7.baidu.com/it/u=825057118,3516313570&fm=193&f=GIF" );

                bannerImages.set("img_url",
                        i==0 ? "http://ldgb.lngbzx.gov.cn/styles/images/middle-banner-7.jpg"
                                : i==1 ? "http://ldgb.lngbzx.gov.cn/styles/images/middle-banner-6.jpg"
                                : "http://ldgb.lngbzx.gov.cn/styles/images/middle-banner-8.jpg" );




//				CourseBase courseBase = CourseBase.dao.findById(bannerImages.getLong("target_id"));
//				CourseLesson courseLesson = courseBase.getCourseLesson();
//				bannerImages.set("assemble_type", courseLesson.getStr("assemble_type"));
//				String target_type = bannerImages.getStr("target_type");
//				if (target_type != null && target_type.equals("course")) {
//					CourseBase courseBase = CourseBase.dao.findById(bannerImages.getLong("target_id"));
//					CourseLesson courseLesson = courseBase.getCourseLesson();
//					bannerImages.set("assemble_type", courseLesson.getStr("assemble_type"));
//				}
                i++;
            }
            dataMap.put("error_code", "0");
            dataMap.put("msg", "success");
            dataMap.put("bannerImages", bannerImagesList);
        }
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 课程热搜关键词
     *
     * @date 2016年11月10日13:42:07
     */
    public void toSearchCourse() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        List<SearchHotKey> searchHotKeyList = SearchHotKey.dao.findAll();
        List list = new ArrayList();
        for (SearchHotKey searchHotKey : searchHotKeyList) {
            list.add(searchHotKey.getStr("hotkey"));
        }
        dataMap.put("error_code", "0");
        dataMap.put("msg", "success");
        dataMap.put("hotlist", list);
        renderJson(JsonKit.mapToJson(dataMap, dataMap.size()));
    }

    /**
     * 获取课程分类
     *
     * @date 2016年11月10日13:42:35
     *
     * @modified 2016年12月29日11:01:12
     */
    public void courseCategoryList() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Integer studentId = getParaToInt("studentId");

        List<CourseCategory> courseCategoryList = CourseCategory.dao.getCourseCategoryList();
        List list = new ArrayList();
        // 分类下的课程数量
        for (int i = 0; i < courseCategoryList.size(); i++) {
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("id", courseCategoryList.get(i).getLong("id"));
            map.put("name", courseCategoryList.get(i).get("name"));
            map.put("pid", courseCategoryList.get(i).getLong("pid"));
            map.put("seq", courseCategoryList.get(i).getInt("seq"));
            map.put("ctype", "0");

//			List<CourseCategory> courseCategorySecondList = CourseCategory.dao.getCourseCategorySecondList(courseCategoryList
//					.get(i).getLong("id"));
//			for (int j = 0; j < courseCategorySecondList.size(); j++) {
//				courseCount = CourseCategoryRelated.dao.getCourseCount(courseCategorySecondList.get(j).getLong("id")) + courseCount;
//			}
//			courseCount = CourseCategoryRelated.dao.getCourseCount(courseCategoryList.get(i).getLong("id")) + courseCount;

            long courseCount = CourseBase.dao.getCourseCount(courseCategoryList.get(i).getLong("id"));
            // 获取二级分类
            courseCount += courseCategorySecondList(courseCategoryList.get(i).getLong("id"), map);
            map.put("courseCount", courseCount);
            list.add(map);
        }
//		Long courseCount = CourseBase.dao.getAllCount();
        dataMap.put("courseCategoryList", list);

        // 年度必修课分类
        courseTopicList(studentId, dataMap);
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 获取二级分类
     */
    public int courseCategorySecondList(Long id, Map<String, Object> map) {
        int secondCourseCount = 0;
        List<CourseCategory> courseCategoryList = CourseCategory.dao.getCourseCategorySecondList(id);
        map.put("num", courseCategoryList.size());
        List list = new ArrayList();
        for (int i = 0; i < courseCategoryList.size(); i++) {
            Map<String, Object> map1 = new HashMap<String, Object>();
            long courseCategoryId = courseCategoryList.get(i).getLong("id");
            long count = CourseBase.dao.getCourseCount(courseCategoryId);
            secondCourseCount += count;

            map1.put("courseCount", count);
            map1.put("secondName", courseCategoryList.get(i).get("name"));
            map1.put("secondId", courseCategoryList.get(i).getLong("id"));
            list.add(map1);
        }
        map.put("secodeArray", list);

        return secondCourseCount;
    }

    /**
     * 年度 必修课
     * @param userId
     * @param map
     */
    public void courseTopicList(Integer studentId, Map<String, Object> map) {
        if (studentId==null || studentId<1) {
            return ;
        }
//		int study_plan_year = SysProperties.dao.getSysPropertiesByName(GlobalConst.STUDY_PLAN_YEAR);
//		if (study_plan_year < 1) {
//			study_plan_year = new Date().getYear() + 1900;
//		}
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        // 年度必修课 一级分类
        Map<String, Object> map_1 = new HashMap<String, Object>();
        map_1.put("topicId", 0);
        map_1.put("name", DateUtil.getYear() + "年度必修课目录");
        map_1.put("pid", -1);
        map_1.put("seq", 0);
        map_1.put("ctype", 1);
        // 年度必修课二级分类
        Student student = Student.dao.findById(studentId);
        String studyGroup = student.getStr("study_group");
        int study_plan_year = Integer.parseInt(DateUtil.getYear());
        StudyPlan studyPlan = StudyPlan.dao.getStudyPlan(study_plan_year, studyGroup);
        if (studyPlan!=null) {
            courseTopicSecondList(studentId, studyPlan.getLong("id"), map_1);
        } else {
            map_1.put("secodeArray", new ArrayList<Map<String, Object>>());
            map_1.put("courseCount", 0);
        }
        list.add(map_1);
        map.put("courseTopicList", list);
    }

    /**
     * 年度必修课二级分类
     */
    public void courseTopicSecondList(long studentId, long studyPlanId, Map<String, Object> map) {
        List<CourseTopic> courseTopicList = CourseTopic.dao.getCourseTopicList(studyPlanId);
        List<Map<String, Object>> list = new ArrayList<Map<String, Object>>();
        Map<String, Object> map_2 = null;
        int courseCount = 0;

        if (courseTopicList!=null) {
            for (CourseTopic vo : courseTopicList) {
                map_2 = new HashMap<String, Object>();
                map_2.put("topicId", vo.getLong("id"));
                map_2.put("name", vo.getStr("topic_name"));
                map_2.put("ctype", 1);

                String courseIds = vo.getStr("course_ids");
                int course_count = courseIds!=null && !"".equals(courseIds)
                        ? courseIds.split(",").length : 0;
                courseCount += course_count;
                map_2.put("courseCount", course_count);
                list.add(map_2);
            }
        }

        map.put("secodeArray", list);
        map.put("courseCount", courseCount);
    }


    /**
     * 根据分类ID获取课程列表
     * /api/cocourseListByCategoryIdurse
     * @modified 2016年12月29日10:16:43
     */
    public void courseListByCategoryId() {
        Map<String, Object> dataMaps = new HashMap<String, Object>();
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();

        Long categoryId = getParaToLong("categoryId");
        Long studentId = getParaToLong("studentId");
        String studyGroup = getPara("studyGroup");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

//        String categoryIds = getSubCategoryIds(categoryId);
//        StudyPlan studyPlan = getLoginStudentYearStudyPlan(studyGroup);
//        String courseIds = getStudyCourses(studyPlan);
//        String excludeIds = CourseTopic.dao.getExcludeCourseIds("33,34");

//        String courseIds = "0";

//        Page<CourseBase> coursePage = CourseBase.dao.getPageCoursesByCategory(
//                null, categoryIds, courseIds + "," + excludeIds,
//                false, studentId, pageNumber, pageSize);

//        Page<CourseBase> coursePage = CourseBase.dao.getPageCoursesByCategory(
//                null, categoryIds, courseIds ,
//                false, studentId, pageNumber, pageSize);

        Page<CourseBase> coursePage = CourseBase.dao.getPageCoursesByCategoryTree(categoryId,pageNumber, pageSize);
        List<CourseBase> list = coursePage.getList();

        for (CourseBase courseBase : list) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
//			courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
//			courseBase.set("small_img", courseBase.getStr("small_img"));
//			courseBase.set("large_img", courseBase.getStr("small_img"));
            courseBase.set("small_img", courseBase.getStr("small_img"));
            courseBase.set("large_img", courseBase.getStr("small_img"));
            dataMap.put("courseBase", courseBase);
            Long cs_id = studentSelected(courseBase.getLong("id"), studentId);
            dataMap.put("selected", cs_id!=null && cs_id>0 ? 1 : 0);
            dataMap.put("courseStudentId", cs_id);
            dataMap.put("courseLesson", courseBase.getCourseLesson());
            dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
            dataMapList.add(dataMap);
            // 课程隐藏功能，2017年2月4日14:44:07 add by zhang.xx
//			if (courseBase != null) {
//				if (courseBase.getInt("level") != 0) {
//					dataMapList.add(dataMap);
//				}
//			}
        }

        dataMaps.put("courseList", dataMapList);
        renderJson(JsonKit.mapToJson(dataMaps, 39));


//		CourseCategory courseCategory = CourseCategory.dao.findById(categoryId);
//		Long pid = courseCategory.getLong("pid");
//		List<CourseCategory> courseCategoryList = CourseCategory.dao
//				.getCourseCategorySecondList(categoryId);
//		int year = sysPropertiesManager.getStudyPlanYear();
//		StudyPlan studyPlan = yearStudyPlanManager.getStudyplanByStudygroupAndYear(student.getStudyGroup(), year);
//		if (pid == 1l) {
//			for (int i = 0; i < courseCategoryList.size(); i++) {
//				Page<CourseCategoryRelated> relatedPage = CourseCategoryRelated
//						.dao.getByCategoryId(courseCategoryList.get(i)
//						.getLong("id"), pageNumber, pageSize);
//				List<CourseCategoryRelated> relatedList = relatedPage.getList();
//
////				List<CourseCategoryRelated> relatedList = CourseCategoryRelated.dao
////						.listByCategoryId(courseCategoryList.get(i).getLong("id"), pageNumber, pageSize);
//				for (CourseCategoryRelated related : relatedList) {
//
//					CourseBase courseBase = CourseBase.dao.findById(related.get("course_id"));
//
//					Map<String, Object> dataMap = new HashMap<String, Object>();
//					courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
//					courseBase.set("small_img", courseBase.getStr("small_img"));
//					courseBase.set("large_img", courseBase.getStr("small_img"));
//					dataMap.put("courseBase", courseBase);
//					dataMap.put("courseLesson", courseBase.getCourseLesson());
//					dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
//					dataMapList.add(dataMap);
//				}
//			}
//		}
//		Page<CourseCategoryRelated> rPage = CourseCategoryRelated.dao
//				.getByCategoryId(categoryId, pageNumber, pageSize);
//		List<CourseCategoryRelated> rList = rPage.getList();
//		for (CourseCategoryRelated related : rList) {
//
//			CourseBase courseBase = CourseBase.dao.findById(related.get("course_id"));
//
//			Map<String, Object> dataMap = new HashMap<String, Object>();
//			courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
//			courseBase.set("small_img", courseBase.getStr("small_img"));
//			courseBase.set("large_img", courseBase.getStr("small_img"));
//			dataMap.put("courseBase", courseBase);
//			dataMap.put("courseLesson", courseBase.getCourseLesson());
//			dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
//			// 课程隐藏功能，2017年2月4日14:44:07 add by zhang.xx
//			if (courseBase != null) {
//				if (courseBase.getInt("level") != 0) {
//					dataMapList.add(dataMap);
//				}
//			}
//		}
//		dataMaps.put("courseList", dataMapList);
//
//		renderJson(JsonKit.mapToJson(dataMaps, 39));
    }

    public Long studentSelected(long courseId, long studentId) {
        CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
        return courseStudent!=null ? courseStudent.getLong("id") : null;
    }


    public String getStudyCourses(StudyPlan studyPlan) {
        if (studyPlan==null) {
            return null;
        }
        StringBuffer result = new StringBuffer();
        List<CourseTopic> courseTopicList = CourseTopic.dao
                .getCourseTopicList(studyPlan.getLong("id"));
        for (int n=0; n<courseTopicList.size(); n++) {
            CourseTopic courseTopic = (CourseTopic)courseTopicList.get(n);
            String courseIds = courseTopic.getStr("course_ids");
            if (courseIds!=null && !"".equals(courseIds.trim())) {
                result.append(courseIds).append(",");
            }
        }

        return result.length()>0 ? result.substring(0, result.length()-1) : "";
    }

    public StudyPlan getLoginStudentYearStudyPlan(String studyGroup) {
        int year = SysProperties.dao.getSysPropertiesByName("study_plan_year");
        StudyPlan studyPlan = StudyPlan.dao.getStudyPlan(year, studyGroup);
        return studyPlan;
    }

    /**
     *    选中节点下的所有课程子分类
     * @return
     */
    private String getSubCategoryIds(Long selectedCategoryId) {
        if (selectedCategoryId==null || selectedCategoryId<1) {
            return null;
        }

        StringBuffer categoryIds = new StringBuffer();
        List<CourseCategory> courseCategorylist = CourseCategory
                .dao.getByIdsLike(selectedCategoryId);
        if (courseCategorylist!=null && courseCategorylist.size()>0) {

            for (int i = 0; i < courseCategorylist.size(); i++) {
                CourseCategory courseCategory = courseCategorylist.get(i);
                categoryIds.append(courseCategory.getLong("id")).append(",");
            }
            categoryIds.append(selectedCategoryId);
        } else {
            categoryIds.append(selectedCategoryId);
        }

        return categoryIds.toString();
    }


	/*public void courseListByCategoryId() {
		Map<String, Object> dataMaps = new HashMap<String, Object>();
		List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
		Long categoryId = getParaToLong("categoryId");
		int pageNumber = getParaToInt("pageNumber");
		int pageSize = getParaToInt("pageSize");
		CourseCategory courseCategory = CourseCategory.dao.findById(categoryId);
		Long pid = courseCategory.getLong("pid");
		List<CourseCategory> courseCategoryList = CourseCategory.dao.getCourseCategorySecondList(categoryId);
		if (pid == 1l) {
			for (int i = 0; i < courseCategoryList.size(); i++) {
				Page<CourseBase> courseBasePage = CourseBase.dao.getByCategoryId(courseCategoryList.get(i).getLong("id"),
						pageNumber, pageSize);
				List<CourseBase> courseBaseList = courseBasePage.getList();
				for (CourseBase courseBase : courseBaseList) {
					Map<String, Object> dataMap = new HashMap<String, Object>();
					courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
					courseBase.set("small_img", courseBase.getStr("small_img"));
					courseBase.set("large_img", courseBase.getStr("small_img"));
					dataMap.put("courseBase", courseBase);
					dataMap.put("courseLesson", courseBase.getCourseLesson());
					dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
					dataMapList.add(dataMap);
				}
			}
		}
		Page<CourseBase> courseBasePage = CourseBase.dao.getByCategoryId(categoryId, pageNumber, pageSize);
		List<CourseBase> courseBaseList = courseBasePage.getList();
		for (CourseBase courseBase : courseBaseList) {
			Map<String, Object> dataMap = new HashMap<String, Object>();
			courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
			courseBase.set("small_img", courseBase.getStr("small_img"));
			courseBase.set("large_img", courseBase.getStr("small_img"));
			dataMap.put("courseBase", courseBase);
			dataMap.put("courseLesson", courseBase.getCourseLesson());
			dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
			dataMapList.add(dataMap);
		}
		dataMaps.put("courseList", dataMapList);
		renderJson(JsonKit.mapToJson(dataMaps, 39));
	}*/

    /**
     * 根据关键词搜索课程
     *
     * 按照title和关键词
     *
     * @modified by zhang.xx
     * @date 2016年11月30日10:26:47
     */
    @Before(KeyCondition.class)
    public void searchCourse() {
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();
        Long studentId = getParaToLong("studentId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        String queryString = getPara("queryString");

        log.error("studentId : " + studentId);

//        StringBuilder sql = new StringBuilder();
        List<Object> paras = new ArrayList<Object>();
//        kcd.buildSql(sql, paras);

        String sql = " FROM t_course_base t WHERE 1=1 AND ( NAME LIKE '%" + queryString + "%' OR tags LIKE '%" + queryString + "%' OR teacher_name LIKE '%" + queryString + "%' OR TYPE LIKE '%" + queryString + "%' OR intro LIKE '%" + queryString + "%' ) " ;
        log.info("search sql : " + sql.toString());
        Page<CourseBase> courseBasePage = CourseBase.dao.getPageLikeQueryString(pageNumber, pageSize, sql.toString(), paras.toArray());

        List<CourseBase> courseBaseList = courseBasePage.getList();
        for (CourseBase courseBase : courseBaseList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
//			courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
//			courseBase.set("small_img", courseBase.getStr("small_img"));
//			courseBase.set("large_img", courseBase.getStr("small_img"));
            courseBase.set("small_img", courseBase.getStr("small_img"));
            courseBase.set("large_img", courseBase.getStr("small_img"));
            dataMap.put("courseBase", courseBase);
            dataMap.put("courseLesson", courseBase.getCourseLesson());
            dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
            dataMap.put("selected", studentSelected(courseBase.getLong("id"), studentId));
            dataMapList.add(dataMap);
        }
        renderJson(JsonKit.listToJson(dataMapList, 39));
    }

    /**
     * 筛选课程
     *
     * @date 2016年11月10日13:30:30
     */
    @Before({ Condition.class })
    public void filterCourse() {
        Map<String, Object> dataMaps = new HashMap<String, Object>();
        List<Map<String, Object>> dataMapList = new ArrayList<Map<String, Object>>();

        StringBuilder sql = new StringBuilder();
        Long studentId = getParaToLong("studentId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        String best = getPara("best");

        Page<CourseBase> courseBasePage = null;
        if (!best.equals("2")) {
            // 最新，好评
            List<Object> paras = new ArrayList<Object>();
            cond.buildSql(sql, paras);
            courseBasePage = CourseBase.dao.findCoursePage(pageNumber, pageSize, sql.toString(), paras.toArray());
        } else {
            // 推荐
            List<CourseStudentClick> courseStudentClicks = CourseStudentClick.dao.findByStudentId(studentId);
            if (courseStudentClicks.size() == 0) {// 没有点击课程
                // 添加级别的限制
                // 获取学员等级
                Student student = Student.dao.findById(studentId);
                int level = student.getInt("level") == null ? 12 : student.getInt("level");

                courseBasePage = CourseBase.dao.getRandomCourses(pageNumber, pageSize, level);
            } else { // 获取相关课程
                courseBasePage = CourseBase.dao.getRelatedCourses(courseStudentClicks, pageNumber, pageSize);
            }
        }

        List<CourseBase> courseBaseList = courseBasePage.getList();
        for (CourseBase courseBase : courseBaseList) {
            Map<String, Object> dataMap = new HashMap<String, Object>();
            courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
            courseBase.set("small_img", courseBase.getStr("small_img"));
            courseBase.set("large_img", courseBase.getStr("small_img"));
            dataMap.put("courseBase", courseBase);
            CourseLesson cl = courseBase.getCourseLesson();
            dataMap.put("courseLesson", cl);
            dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
            if (!"4".equals(cl.get("assemble_type"))) {
                dataMapList.add(dataMap);
            }
        }
        dataMaps.put("courseList", dataMapList);

        renderJson(JsonKit.mapToJson(dataMaps, 39));
    }


/********************************* 进入课程播放页面  * start********************************/
    /**
     * 课程详情
     *
     * @date 2016年11月10日11:28:40
     */
    public void getCourseInfo() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Long studentId = getParaToLong("studentId");
        Long courseId = getParaToLong("id");

        // 课程信息
        CourseBase courseBase = CourseBase.dao.findById(courseId);
//		courseBase.set("audiences", CommonUtil.getMediaUrl(courseBase));
        courseBase.set("small_img", courseBase.getStr("small_img"));
        courseBase.set("large_img", courseBase.getStr("small_img"));

        // 课件信息
        CourseLesson lesson = courseBase.getCourseLesson();

        long watchId = 0;
        // 学员看课数据
        LessonStudentRecord lessonStudentRecord = null;
        CourseStudent courseStudent = CourseStudent.dao.findByCourseIdAndStudentId(courseId, studentId);
        if (courseStudent != null) {
            // 新增看课记录
            lessonStudentRecord = makeNewLessonStudentRecord(courseStudent, lesson.getLong("id"));
            watchId = lessonStudentRecord.getLong("id");
            // 更新
            studyCourse(courseStudent, lessonStudentRecord);
            dataMap.put("selected", 1);
        } else {
            dataMap.put("selected", 0);
        }

        // 浏览数
        CourseLesson courseLesson = courseBase.getCourseLesson();
        int viewedNum = NumberUtil.convertInt(courseLesson.getInt("viewed_num"));
        courseLesson.set("viewed_num", viewedNum + 1);
        courseLesson.update();

        // 练习题的查错 2016年12月7日11:27:21
        List<Question> questionList = Question.dao.findByCourseId(courseId, "course");
        if (questionList.size() != 0) {
            for (Question question : questionList) {
                List<QuestionMetas> questionMetasList = QuestionMetas.dao
                        .getQuestionMetas(Long.valueOf(question.getBigInteger("id").toString()));
                for (int j = 0; j < questionMetasList.size(); j++) {
                    QuestionMetas questionMetas = (QuestionMetas) questionMetasList.get(j);
                    question.set("item" + (j + 1) + "_id", questionMetas.get("options"));
                }
            }
            dataMap.put("questionList", questionList);
        } else {
            dataMap.put("msg", "暂无练习");
        }

        dataMap.put("courseBase", courseBase);
        dataMap.put("courseLesson", courseBase.getCourseLesson());
        dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
        dataMap.put("courseStudent", courseStudent);
        dataMap.put("watchId", watchId);
        dataMap.put("courseSelectedNum", courseBase.getCount(courseId));
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 初始化听课计时（t_lesson_student_record表新增一条数据）
     */
    public LessonStudentRecord makeNewLessonStudentRecord(CourseStudent courseStudent, long lessonId) {
        LessonStudentRecord lessonStudentRecord = new LessonStudentRecord();
        lessonStudentRecord.set("course_student_id", courseStudent.getLong("id"));
        lessonStudentRecord.set("course_id", courseStudent.getLong("course_id"));
        lessonStudentRecord.set("student_id", courseStudent.getLong("student_id"));
        lessonStudentRecord.set("learned_ip", super.getRequest().getRemoteAddr());
        lessonStudentRecord.set("learned_hour",0);
        lessonStudentRecord.set("lesson_id", lessonId);
        lessonStudentRecord.set("learned_position", 0);
        lessonStudentRecord.set("learned_starttime", new Date());
        lessonStudentRecord.set("target_id", courseStudent.getLong("target_id"));
        lessonStudentRecord.set("target_type", courseStudent.getStr("target_type"));

        LessonStudentRecord.dao.save(lessonStudentRecord);
        return lessonStudentRecord;
    }

    /**
     *
     * @param lessonStudentRecord
     */
    public void studyCourse(CourseStudent courseStudent, LessonStudentRecord lessonStudentRecord) {

        int learnedTimes = NumberUtil.convertDouble(courseStudent.getDouble("learned_times"));
        courseStudent.set("learned_times", learnedTimes + 1);
        courseStudent.set("last_learned_time", new Date());
        courseStudent.set("last_learned_ip", lessonStudentRecord.getStr("learned_ip"));
        courseStudent.update();

        StudentCount studentCount = StudentCount.dao.findByStudentId(courseStudent.getLong("student_id"));
        if (studentCount==null) {
            studentCount = createStudentCount(courseStudent.getLong("student_id"));
        }
        studentCount.set("current_watch_id", lessonStudentRecord.getLong("id"));
        StudentCount.dao.update();
    }


    private StudentCount createStudentCount(Long studentId) {
        StudentCount studentCount = new StudentCount();
        studentCount.set("comment_num", 0);
        studentCount.set("course_num", 0);
        studentCount.set("credit_level_chn_name", "");
        studentCount.set("credit_level_img", "");
        studentCount.set("credit_level_seq", 0);
        studentCount.set("credit_num", 0);
        studentCount.set("friend_num", 0);
        studentCount.set("last_learn_courses", "");
        studentCount.set("week_study_hour", 0);
        studentCount.set("month_study_hour", 0);
        studentCount.set("year_study_hour", 0);
        studentCount.set("study_plan_id", 0);
        studentCount.set("student_id", studentId);
        studentCount.set("sp_course_hour", 0);
        studentCount.set("sp_reuired_ch", 0);
        studentCount.set("sp_finished_reuired_ch", 0);
        studentCount.set("sp_optional_ch", 0);
        studentCount.set("sp_finnished_optional_ch", 0);
        studentCount.set("note_num", 0);
        studentCount.save();

        return studentCount;
    }
/*************************** 课程播放页 * End********************************/


    /**
     * 分页获取课程 详情页面评论
     *
     * @date 2016年11月10日13:30:08
     */
    public void courseComment() {
        Long courseId = getParaToLong("id");
        Long studentId = getParaToLong("studentId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");
        Page<Comment> commentPage = Comment.dao.findCommentPage(pageNumber, pageSize, courseId);
        List<Comment> commentList = commentPage.getList();
        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                CourseCommentCkGood courseCommentCkGood = CourseCommentCkGood.dao.getCommentCkGood(courseId, studentId,
                        comment.getLong("id"));
                if (courseCommentCkGood != null) {
                    comment.set("commentPrise", 1);
                } else {
                    comment.set("commentPrise", 0);
                }
            }

            for (int i = 0; i < commentList.size(); i++) {
                Student student = Student.dao.findById(commentList.get(i).getLong("create_userid"));
                int num = (int) (Math.random() * 22) + 1;
                if (student.getStr("little_img") == null || "".equals(student.getStr("little_img"))) {
                    commentList.get(i).set("student_head_img", CommonUtil.getRandomHeadImgUrl(num));
                } else {
                    commentList.get(i).set("student_head_img", CommonUtil.getHeadImgUrl(student));
                }
            }
        }
        dataMap.put("commentList", commentList);
        dataMap.put("commentNum", commentList.size());
        // 评论总数
        dataMap.put("commentTotalNum", Comment.dao.getTotalComment("course", courseId));
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * 分页获取资讯 详情页面评论
     *
     * @date 2016年12月21日16:37:46
     */
    public void articleComment() {

        Long articleId = getParaToLong("articleId");
        Long studentId = getParaToLong("studentId");
        int pageNumber = getParaToInt("pageNumber");
        int pageSize = getParaToInt("pageSize");

        Page<Comment> commentPage = Comment.dao.findArticleCommentPage(pageNumber, pageSize, articleId);
        List<Comment> commentList = commentPage.getList();

        Map<String, Object> dataMap = new HashMap<String, Object>();
        if (commentList != null) {
            for (Comment comment : commentList) {
                ArticleCommentCkGood articleCommentCkGood = ArticleCommentCkGood.dao.getCommentCkGood(articleId, studentId,
                        comment.getLong("id"));
                if (articleCommentCkGood != null) {
                    comment.set("commentPrise", 1);
                } else {
                    comment.set("commentPrise", 0);
                }
            }

            for (int i = 0; i < commentList.size(); i++) {
                Student student = Student.dao.findById(commentList.get(i).getLong("create_userid"));
                int num = (int) (Math.random() * 22) + 1;
                if (student.getStr("little_img") == null || "".equals(student.getStr("little_img"))) {
                    commentList.get(i).set("student_head_img", CommonUtil.getRandomHeadImgUrl(num));
                } else {
                    commentList.get(i).set("student_head_img", CommonUtil.getHeadImgUrl(student));
                }
            }
        }

        dataMap.put("commentList", commentList);
        dataMap.put("commentNum", commentList.size());
        // 评论总数
        dataMap.put("commentTotalNum", Comment.dao.getTotalComment("article", articleId));

        renderJson(JsonKit.mapToJson(dataMap, 39));
    }

    /**
     * IOS根据课程ID获取课程详情
     */
    public void getCourse() {
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Long courseId = getParaToLong("courseId");
        CourseBase courseBase = CourseBase.dao.findById(courseId);
        courseBase.set("url", CommonUtil.getMediaUrl(courseBase));
        courseBase.set("small_img", courseBase.getStr("small_img"));
        courseBase.set("large_img", courseBase.getStr("small_img"));
        dataMap.put("courseBase", courseBase);
        dataMap.put("courseLesson", courseBase.getCourseLesson());
        dataMap.put("courseLearningSetting", courseBase.getCourseLearningSetting());
        renderJson(JsonKit.mapToJson(dataMap, 39));
    }
    /**
     * 四门热门微课
     */
    public void fourHotCourse(){
        Map<String, Object> dataMap = new HashMap<String, Object>();
        dataMap.put("hotCourses", CourseBase.dao.getFourCompetitiveCourses());
        renderJson(JsonKit.mapToJson(dataMap, GlobalConst.DEFAULT_DEPTH));
    }

    public void getCourseMetadata(){
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Long courseId = getParaToLong("courseId");
        dataMap.put("courseMetadata", CourseLearningSetting.dao.findByCourseId(courseId));
        renderJson(JsonKit.mapToJson(dataMap, GlobalConst.DEFAULT_DEPTH));
    }

    public void getCourseCategory(){
        Map<String, Object> dataMap = new HashMap<String, Object>();
        Long courseId = getParaToLong("courseId");
        CourseBase courseBase = CourseBase.dao.findById(courseId);
        CourseCategory courseCategory = CourseCategory.dao.findById(courseBase.getLong("category_id"));
        dataMap.put("courseCategory", courseCategory);
        renderJson(JsonKit.mapToJson(dataMap, GlobalConst.DEFAULT_DEPTH));
    }
}

